// class Height {
//     constructor(h,ind) {
//
//     }
//
// }
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function(height) {

    if (height.length < 3) {
        return 0;
    }

    let sum = 0,
        sq = height.length;
    height = height.map((h,ind) => {
        sum += h;
        return {h: h,index: ind};
    }).sort((a,b) => {
        return b.h - a.h;
    });


    let filt = [height[0]];
    let left = height[0].index;
    let right = height[0].index;
    let count = height.length;
    for (let i = 1;i < count;i++) {
        if (height[i].index < left) {
            left = height[i].index;
            filt.push(height[i])
        } else if (height[i].index > right) {
            right = height[i].index;
            filt.push(height[i]);
        }
        if (left === 0 && right === count - 1) {
            break;
        }
    }
    let max = filt[0].h;
    height = filt.sort((a,b) => a.index - b.index);
    let maxIndex = [-1,-1];
    // console.log(height);
    // console.log(maxIndex);
    count = height.length;
    for (let i = 0;i < count;i++) {
        if (height[i].h === max) {
            if (maxIndex[0] === -1) {
                maxIndex[0] = i;//height[i].index;
            } else {
                maxIndex[1] = i;//height[i].index;
            }
            // break;
        }
    }
    if (maxIndex[1] === -1) {
        maxIndex[1] = maxIndex[0];
    }
    // console.log(height);
    // console.log(maxIndex);

    let getSum = (arr,maxObj) => {
        if (arr.length === 0) {
            return 0;
        }
        // let dir = 1;
        let sum = 0;
        let pre = arr[0];
        arr.forEach((a,ind) => {
            if (ind) {
                sum -= (a.h - pre.h) * (maxObj.index - a.index);
                pre = a;
            } else {
                sum = (maxObj.h - a.h) * (maxObj.index - a.index);
                if (pre.h >= a.h) {
                    return;
                }
                pre = a;
            }
        });
        // console.log(`sum = ` + sum);
        return Math.abs(sum);
    };

    sum += getSum(height.slice(0,maxIndex[0]),height[maxIndex[0]]);
    sum += getSum(height.slice(maxIndex[1]+ 1).reverse(),height[maxIndex[1]]);

    // console.log(sq * height[maxIndex].h - sum);
    return sq * height[maxIndex[0]].h - sum;
};

module.exports = {
    trap
}
